package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.RequisitionUnPunch;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class CheckUnpunchFragment extends CheckDetailFragment {
  private static final String SIGN_IN_STRING = "RegIn";
  private static final String SIGN_OUT_STRING = "RegOut";
  private EditText mEtReason;
  private TextView mTvActualTime;
  //private TextView mTvUnpunchType;
  private RadioButton mRbSignIn;
  private RadioButton mRbSignOut;
  /** 签到类型 */
  private String mSignType = "";
  private TextView mTvUnpunchReference;
  private String mReferenceName = "";
  private String mReferenceJobNO = "";
  protected static final int REQUEST_ACTUAL_DATE = 2;
  //证明人
  protected static final int REQUEST_REFERENCE = 3;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    setTitleCustom(R.string.requisitionunpunch);
    View view = inflater.inflate(R.layout.fragment_check_unpunch, container, false);
    findViews(view);
    initDetailData();

    return view;
  }

  private void findViews(View v) {
    mEtReason = (EditText) v.findViewById(R.id.et_overTimeReason_checkOver);
    mTvActualTime = (TextView) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    //		mTvUnpunchType = (TextView) v.findViewById(R.id.tv_unpunch_type);
    /**打卡类型*/
    /* 打卡类型 */
    RadioGroup mRgSignType = (RadioGroup) v.findViewById(R.id.rg_signType);
    mRbSignIn = (RadioButton) v.findViewById(R.id.rb_signIn);
    mRbSignOut = (RadioButton) v.findViewById(R.id.rb_signOut);

    mTvUnpunchReference = (TextView) v.findViewById(R.id.tv_reference);
    mTvUnpunchReference.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View arg0) {
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, REQUEST_REFERENCE);
      }
    });
    //		mTvUnpunchType.setOnClickListener(new OnClickListener() {
    //
    //			@Override
    //			public void onClick(View v) {
    //				// Auto-generated method stub
    //				showDialogSignType();
    //			}
    //		});
    mRgSignType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.rb_signIn:
            mSignType = SIGN_IN_STRING;
            break;
          case R.id.rb_signOut:
            mSignType = SIGN_OUT_STRING;
            break;
        }
      }
    });
    mTvActualTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE);
      }
    });

    if (mMenuType == WAIT_CHECK || mMenuType == CHECK_PASS) {
      mEtReason.setEnabled(false);
      mTvActualTime.setEnabled(false);
      //			mTvUnpunchType.setEnabled(false);
      mRbSignOut.setEnabled(false);
      mRbSignIn.setEnabled(false);
      mTvUnpunchReference.setEnabled(false);
    }
  }

  private void showDialog(String startDate, int titleId, int requestCode) {

    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(CheckUnpunchFragment.this, requestCode);
    dialog.show(fm, "");
  }

  /**
   * 显示选择打卡类型dialog
   */
  //@SuppressWarnings("unused") protected void showDialogSignType() {
  //  new AlertDialog.Builder(getActivity()).setSingleChoiceItems(new String[] {
  //      getResources().getString(R.string.sign_in), getResources().getString(R.string.sign_out)
  //  }, 0, new DialogInterface.OnClickListener() {
  //    public void onClick(DialogInterface dialog, int which) {
  //      switch (which) {
  //        case 0:
  //          mSignType = SIGN_IN_STRING;
  //          mTvUnpunchType.setText(R.string.sign_in);
  //          break;
  //        case 1:
  //          mSignType = SIGN_OUT_STRING;
  //          mTvUnpunchType.setText(R.string.sign_out);
  //          break;
  //
  //        default:
  //          break;
  //      }
  //      dialog.dismiss();
  //    }
  //  }).show();
  //}

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;

    // 更新
    if (requestCode == REQUEST_ACTUAL_DATE) {

      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualTime.setText(dateString);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    if (requestCode == REQUEST_REFERENCE && data != null) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);

      mReferenceName = customer.getName();// 证明人姓名
      mReferenceJobNO = customer.getId();// 证明人工号
      mTvUnpunchReference.setText(mReferenceName);
    }
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mType + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private void initDetailData() {

    if (mMenuType != ADD) {
      volleypostInit();
    }
  }

  private void volleypostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", mType);
    params.put("id", mId);

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) {

        MyUtils.dismissDialog();
        try {
          RequisitionUnPunch requisitionDetail =
              new Gson().fromJson(response, RequisitionUnPunch.class);

          mEtReason.setText(requisitionDetail.getUnpunchReason());
          mTvActualTime.setText(requisitionDetail.getActTime());
          mReferenceName = requisitionDetail.getDemonstrateStaffName();
          mReferenceJobNO = requisitionDetail.getDemonstrateStaffId();
          mTvUnpunchReference.setText(mReferenceName);

          if (SIGN_IN_STRING.equalsIgnoreCase(requisitionDetail.getPunchKind())) {
            //						mTvUnpunchType.setText(R.string.sign_in);
            mRbSignIn.setChecked(true);
            mRbSignOut.setChecked(false);
            mSignType = SIGN_IN_STRING;
          }
          if (SIGN_OUT_STRING.equalsIgnoreCase(requisitionDetail.getPunchKind())) {
            //						mTvUnpunchType.setText(R.string.sign_out);
            mRbSignIn.setChecked(false);
            mRbSignOut.setChecked(true);
            mSignType = SIGN_OUT_STRING;
          }
        } catch (JsonSyntaxException e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.noConnectionToServer);
      }
    });
  }

  @Override public boolean isCorrectInput() {
    String currentTime = DateUtil.dateToString(new Date());// 当前时间
    String reasonString = mEtReason.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      ToastUtil.show(R.string.no_content);
      return false;
    }
    String punchTime = mTvActualTime.getText().toString().trim();
    if (TextUtils.isEmpty(punchTime)) {
      ToastUtil.show(R.string.no_punchTime);
      return false;
    }

    //		String punchTypeString = mTvUnpunchType.getText().toString().trim();
    //		if (TextUtils.isEmpty(punchTypeString)) {
    //			Toast.makeText(getActivity(), R.string.no_punchType, Toast.LENGTH_SHORT).show();
    //			return false;
    //		}

    if (TextUtils.isEmpty(mSignType)) {
      ToastUtil.show(R.string.no_punchType);
      return false;
    }
    if (DateUtil.before(currentTime, punchTime)) {
      ToastUtil.show(R.string.realTimeBeforeCurrent);
      return false;
    }

    if (TextUtils.isEmpty(mTvUnpunchReference.getText().toString().trim())) {
      ToastUtil.show(R.string.noReference);
      return false;
    } else {
      //证明人是当前登录人不可启动流程
      if (mReferenceJobNO.equalsIgnoreCase(CurrentUser.newInstance(getActivity()).getJobNumber())) {
        ToastUtil.show(R.string.noSelf);
        return false;
      }
    }

    return true;
  }

  @Override protected void volleyPostSave(final String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);

    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", CheckDetailFragment.VALUE_UNPUNCH);
    params.put("saveOrRun", type);
    params.put("punchKind", mSignType);
    params.put("actTime", mTvActualTime.getText().toString().trim());
    params.put("unpunchReason", mEtReason.getText().toString().trim());
    params.put("demonstrateStaffId", mReferenceJobNO);
    params.put("demonstrateStaffName", mReferenceName);

    if (mMenuType != ADD) {
      params.put("id", mId);
      if (TYPE_RUN.equals(type)) {
        params.put("isList", "0");
      }
    }
    if ("abort".equalsIgnoreCase(mDataStatus)) {
      params.put("dataStatus", "new");
    }

    if (mMenuType == WAIT_CHECK) LogUtil.i("overParams=" + params.toString());
    if (TYPE_RUN.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    }
    if (TYPE_SAVE.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    }

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          switch (successType) {
            case "1":
              getActivity().setResult(Activity.RESULT_OK);
              ToastUtil.show(R.string.success_operation);
              getActivity().finish();
              break;
            case "0":
              //						Toast.makeText(getActivity(), successsMessage.getMessage(), Toast.LENGTH_SHORT).show();
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }
}
